package com.agileai.portal.controller.uui;

import java.util.Date;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.bizmoduler.uui.UserLocalManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserModel;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.CryptionUtil;

public class UserRegistryHandler
        extends BaseHandler {
	
    public UserRegistryHandler() {
        super();
        this.serviceId = buildServiceId(SecurityGroupManage.class);
    }

    protected SecurityGroupManage getService() {
        return (SecurityGroupManage) this.lookupService(this.getServiceId());
    }
    
    @PageAction
	public ViewRenderer registryUser(DataParam param){
		boolean registryResult = false;
		String userName = param.get("USER_CODE");
		String mailAddress = param.get("USER_MAIL");
		if (syncRemoteUser(param)){
			registryResult = createLocalRecord(param);
		}
		String url = "";
		if (registryResult){
			if (sendActiveMail(userName, mailAddress)){
				url = getHandlerURL(RegistryResultHandler.class)+"&operaType=userRegistry&result=success&mailAddress="+mailAddress;
			}else{
				this.deleteUser(userName);
				url = getHandlerURL(RegistryResultHandler.class)+"&operaType=userRegistry&result=failure&mailAddress="+mailAddress;				
			}
		}else{
			url = getHandlerURL(RegistryResultHandler.class)+"&operaType=userRegistry&result=failure&mailAddress="+mailAddress;
		}
		return new RedirectRenderer(url);
	}
	
    private boolean syncRemoteUser(DataParam param){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("createUser");
    		UserModel userModel = new UserModel();
    		userModel.setId(param.get("USER_CODE"));
    		userModel.setMail(param.get("USER_MAIL"));
    		userModel.setPassword(param.get("USER_PWD"));
    		userModel.setStatus("-1");
    		ResultStatus resultStatus = userSync.createUser(tokenId, userModel);
    		result = resultStatus.isSuccess();
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }
    
    private boolean deleteUser(String userCode){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("removeUser");
    		userSync.removeUser(tokenId, userCode);			
    		
    		SecurityAuthorizationConfig securityAuthorizationConfig = (SecurityAuthorizationConfig)this.lookupService("securityAuthorizationConfigService");
    		securityAuthorizationConfig.deleteUser(userCode);
    		result = true;
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
		return result;
    }
    
    private boolean sendActiveMail(String userCode,String mailAddress){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("sendMail");
    		String storeTokenId = String.valueOf(System.currentTimeMillis());
			String mailContent = UserSyncHelper.createRegistryMailContent(userCode, storeTokenId);
			mailContent = mailContent.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");  
			String mailSubject = "数通畅联--账户激活链接";
			ResultStatus resultStatus = userSync.sendMail(tokenId, mailAddress,mailSubject,mailContent);
			
			if (resultStatus.isSuccess()){
				Date storeTokenTime = new Date();
				UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
				userLocalManage.updateUserTokends(userCode, storeTokenId, storeTokenTime);
				result = true;
			}
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;    	
    }
    
    private boolean createLocalRecord(DataParam pageParam){
    	boolean result = false;
//    	USER_ID,USER_CODE,USER_NAME,USER_PWD,USER_SEX,USER_DESC,USER_STATE,USER_SORT,USER_MAIL,USER_PHONE
    	try {
        	DataParam param = new DataParam();
        	param.put("USER_CODE",pageParam.get("USER_CODE"));
        	param.put("USER_NAME",pageParam.get("USER_NAME"));
        	param.put("USER_PWD",pageParam.get("USER_PWD"));
        	param.put("USER_MAIL",pageParam.get("USER_MAIL"));
        	param.put("USER_SEX","N");
        	param.put("USER_STATE","0");
        	param.put("USER_SORT",0);
        	
        	String tabId = "SecurityUser";
    		SecurityGroupManage service = getService();
    		String colIdField = service.getTabIdAndColFieldMapping().get(tabId);
    		param.put(colIdField,"D3659EC9-162D-41B1-B1D1-13AC4CC955D4");
    		String userPassword = param.get("USER_PWD");
    		String encodePassword = CryptionUtil.md5Hex(userPassword);
    		param.put("USER_PWD",encodePassword);
    		service.createtContentRecord(tabId,param);	
    		result = true;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }
    
	@PageAction
	public ViewRenderer checkUserInfo(DataParam param){
		String rspText = "";
		String valideCode = param.get("valideCode");
		String safecode = (String)this.request.getSession().getAttribute("safecode");
		if (safecode != null && safecode.equals(valideCode)){
			UserLocalManage securityAuthorizationConfig = (UserLocalManage)this.lookupService(UserLocalManage.class);
			String userCode = param.get("USER_CODE");
			DataRow row = securityAuthorizationConfig.retrieveUserRecord(userCode);
			if (row != null && !row.isEmpty()){
				rspText = "该用户名已被注册，请尝试其他用户名！"; 
			}
		}else{
			rspText = "验证码不正确！";
		}
		return new AjaxRenderer(rspText);
	}
}